package com.ruoyi.classai.config.interceptor;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.CacheConstants;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.context.ThirdSessionHolder;
import com.ruoyi.common.core.domain.ThirdSession;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * api接口拦截器
 * @author lcj
 */
@Slf4j
@Component
@AllArgsConstructor
public class ApiInterceptor implements HandlerInterceptor {

    private final RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //前端认证
        String thirdSessionHeader=request.getHeader("third-session");
        if(StrUtil.isNotBlank(thirdSessionHeader)){
            String cacheToken = redisService.getCacheObject(CacheConstants.API_TOKEN_CACHE+thirdSessionHeader);
            if (StrUtil.isEmpty(cacheToken)) {
                returnJson(response, AjaxResult.error(HttpStatus.UNAUTHORIZED, "token 已过期,请重新登录"));
                return false;
            }
            //获取信息
            ThirdSession thirdSession = JSONObject.parseObject(cacheToken, ThirdSession.class);
            //设置thirdSession
            ThirdSessionHolder.setThirdSession(thirdSession);
            //更新token
            redisService.setCacheObject(CacheConstants.API_TOKEN_CACHE+thirdSessionHeader, JSONObject.toJSONString(thirdSession),30L, TimeUnit.DAYS);
            return true;
        }else {
            returnJson(response, AjaxResult.error(HttpStatus.UNAUTHORIZED, "接口验证失败"));
            return false;
        }
    }


    /**
     * 返回参数
     * @param response response
     * @param json 参数
     */
    public void returnJson(HttpServletResponse response, Object json) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        try {
            response.getWriter().write(JSONObject.toJSONString(json));
            response.getWriter().close();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}
